package com.marketing.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.marketing.auth.entity.Permission;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 权限Mapper接口
 */
@Mapper
public interface PermissionMapper extends BaseMapper<Permission> {

    /**
     * 根据用户ID查询用户的所有权限
     * @param userId 用户ID
     * @return 权限列表
     */
    @Select("SELECT DISTINCT p.* FROM sys_permission p " +
            "INNER JOIN sys_role_permission rp ON p.id = rp.permission_id " +
            "INNER JOIN sys_user_role ur ON rp.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND p.status = 1")
    List<Permission> selectPermissionsByUserId(@Param("userId") Long userId);

    /**
     * 根据角色ID查询角色的所有权限
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Select("SELECT p.* FROM sys_permission p " +
            "INNER JOIN sys_role_permission rp ON p.id = rp.permission_id " +
            "WHERE rp.role_id = #{roleId} AND p.status = 1")
    List<Permission> selectPermissionsByRoleId(@Param("roleId") Long roleId);

    /**
     * 查询所有启用的权限
     * @return 权限列表
     */
    @Select("SELECT * FROM sys_permission WHERE status = 1 ORDER BY id ASC")
    List<Permission> selectEnabledPermissions();

    /**
     * 根据权限编码查询权限
     * @param permissionCode 权限编码
     * @return 权限信息
     */
    @Select("SELECT * FROM sys_permission WHERE permission_code = #{permissionCode} AND status = 1")
    Permission selectByPermissionCode(@Param("permissionCode") String permissionCode);

    /**
     * 根据资源ID查询权限
     * @param resourceId 资源ID
     * @return 权限列表
     */
    @Select("SELECT * FROM sys_permission WHERE resource_id = #{resourceId} AND status = 1")
    List<Permission> selectByResourceId(@Param("resourceId") Long resourceId);
}